<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Download extends Admin_Controller
{
	public function __construct()
	{
		parent::__construct();

		$this->load->model('download_model');

		$this->load->helper(array('file', 'string'));

		$this->template->set_breadcrumb('Download', 'backend/download');
		// ZIP, RAR, 7Z, DOC, DOCX, PDF, JPG, PNG, GIF, BMP, XLS, XLSX, PPT, PPTX
	}

	public function index()
	{
		$this->template->title('SiteName', 'Download');
		$this->template->build('backend/download/download', $this->data);
	}

	public function load($order_by = 'id', $order_dir = 'desc', $page = 1)
	{
		$pager_config['base_url'] = base_path() . "backend/download/load/{$order_by}/{$order_dir}/";
		$pager_config['uri_segment'] = 6;
		$pager_config['num_links'] = 3;
		$pager_config['total_rows'] = $this->download_model->count();
		$pager_config['per_page'] = 20;

		$limit = $pager_config['per_page'];
		$offset = $page ? (($page - 1) * $limit) : 0;
		$downloads = $this->download_model->find(NULL, "{$order_by} {$order_dir}", $limit, $offset)->result();
		$data['sql'] = $this->db->last_query();

		$data['rows'] = "";
		foreach ($downloads as $row)
		{
			$data['rows'].= "<tr><td><input type=\"checkbox\" name=\"items[]\" value=\"{$row->id}\" /></td>";
			$data['rows'].= "	<td>" . $row->name . "</td>";
			$data['rows'].= "	<td>" . $row->description . "</td>";
			$data['rows'].= "	<td>" . $row->file_type . "</td>";
			$data['rows'].= "	<td>" . $row->file_size . "</td>";
			$data['rows'].= "	<td>" . $row->file_hits . "</td>";
			$data['rows'].= "	<td align=\"center\"><div><a href=\"". base_path() . "backend/download/update/{$row->id}\" class=\"edit\">Edit</a></div></td></tr>";
		}

		$data['from_record'] = $pager_config['total_rows'] == 0 ? 0 : $offset + 1;
		$data['to_record'] = $offset + $limit > $pager_config['total_rows'] ? $pager_config['total_rows'] : $offset + $limit;
		$data['total_record'] = $pager_config['total_rows'];

		$this->pagination->initialize($pager_config);
		$data['pagination'] = $this->pagination->create_links();
		$data['message'] = 'OK';

		echo json_encode($data);
	}

	public function create()
	{
		$this->data['scripts'][] = $this->data['base_url'] . 'assets/js/jquery.ajaxfileupload.js';
		$this->data['message'] = '';

		$validator = $this->form_validation;
		$validator->set_rules('name', 'Tên', 'trim|required|xss_clean|min_length[3]|max_length[32]');
		$validator->set_rules('description', 'Mô tả', 'trim|xss_clean');

		$validator->set_rules('file_name', 'File', 'trim|required|xss_clean');
		$validator->set_rules('file_path', 'Đường dẫn', 'trim|required|xss_clean');
		$validator->set_rules('file_type', 'Kiểu file', 'trim|xss_clean');
		$validator->set_rules('file_size', 'Kích cỡ', 'trim|xss_clean');
		if($validator->run())
		{
			$data['name'] = $validator->set_value('name');
			$data['description'] = $validator->set_value('description');

			$data['file_name'] = $validator->set_value('file_name');
			$data['file_path'] = $validator->set_value('file_path');
			$data['file_type'] = $validator->set_value('file_type');
			$data['file_size'] = $validator->set_value('file_size');
			$data['created'] = date('Y-m-d H:i:s');

			$this->download_model->insert_ignore($data);
			$this->data['message'] = 'Dữ liệu thêm vào thành công';
		}
		else
		{
			$this->data['message'] = validation_errors();
		}

		$this->template->set_breadcrumb('Tạo mới', 'backend/download/create');
		$this->template->title('SeoShop', 'Download', 'Tạo mới');
		$this->template->build('backend/download/create', $this->data);
	}

	public function update($download_id = NULL)
	{
		if($download_id)
		{
			$this->data['message'] = '';

			$validator = $this->form_validation;
			$validator->set_rules('name', 'Tên', 'trim|required|xss_clean|min_length[3]|max_length[32]');
			$validator->set_rules('description', 'Mô tả', 'trim|xss_clean');

			$validator->set_rules('file_name', 'File', 'trim|required|xss_clean');
			$validator->set_rules('file_path', 'Đường dẫn', 'trim|required|xss_clean');
			$validator->set_rules('file_type', 'Kiểu file', 'trim|xss_clean');
			$validator->set_rules('file_size', 'Kích cỡ', 'trim|xss_clean');
			if($validator->run())
			{
				$data['name'] = $validator->set_value('name');
				$data['description'] = $validator->set_value('description');

				$data['file_name'] = $validator->set_value('file_name');
				$data['file_path'] = $validator->set_value('file_path');
				$data['file_type'] = $validator->set_value('file_type');
				$data['file_size'] = $validator->set_value('file_size');

				$this->download_model->update($data);
				$this->data['message'] = 'Dữ liệu thêm vào thành công';
			}
			else
			{
				$this->data['message'] = validation_errors();
			}

			$this->data['download'] = $this->download_model->find(array('id' => $download_id))->row();
			$this->template->title('SiteName', 'Download', 'Chỉnh sửa');
			$this->template->build('backend/download/update', $this->data);
		}
		else
		{
			show_404();
		}
	}

	public function upload()
	{
		$data['error'] = false;

		$config['upload_path'] = './assets/uploads/files';
		$config['allowed_types'] = 'zip|rar|7z|doc|docx|pdf|jpg|png|gif|xls|xlsx|ppt|pptx'; // @XXX Configable

		$this->load->library('upload', $config);
		if ( ! $this->upload->do_upload('file_upload'))
		{
			$data['error'] = true;
			$data['response'] = $this->upload->display_errors("", "\n");
		}
		else
		{
			$data['response'] = $this->upload->data();
		}

		echo json_encode($data);
		return;
	}

	public function delete($download_id = NULL)
	{
		if($this->input->is_ajax_request())
		{
			if($download_ids = $this->input->post('items'))
			{
				foreach ((array)$download_ids as $download_id)
				{
					//@XXX Delete file ?
					$this->download_model->delete(array('id' => $download_id));
				}
			}

			$data['message'] = 'OK';
			die(json_encode($data));
		}
	}
}